package com.weixing.mall.base.utils;

import com.weixing.mall.base.constant.GlobalConstant;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * 验签工具类
 *
 * @author  siashan
 * @since v1.0
 */
public class SignUtil {

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param signType 签名方式
     * @throws Exception 不合法的签名异常
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data,String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(GlobalConstant.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) {
                // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.deleteCharAt(sb.lastIndexOf("&"));
        if (GlobalConstant.SIGN_TYPE_MD5.equals(signType)) {
            System.out.println(sb.toString());
            String s = MD5(sb.toString()).toUpperCase();
            System.out.println(s);
            return s;
        } else if (GlobalConstant.SIGN_TYPE_HMACSHA256.equals(signType)) {
            return HMACSHA256(key,sb.toString());
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @throws Exception 未知异常
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance(GlobalConstant.SIGN_TYPE_MD5);
        byte[] array = md.digest(data.getBytes(GlobalConstant.CHARSET_UTF8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256(对称加密)
     *
     * @param data 待处理数据
     * @param key 秘钥
     * @return 加密结果
     * @throws Exception    未知异常
     */
    public static String HMACSHA256(String key ,String data) throws Exception {
        Mac sha256_HMAC = Mac.getInstance(GlobalConstant.SIGN_TYPE_HMACSHA256);
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(GlobalConstant.CHARSET_UTF8), GlobalConstant.SIGN_TYPE_HMACSHA256);
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes(GlobalConstant.CHARSET_UTF8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
}
